#include "aiclient.h"
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QNetworkRequest>
#include <QUrl>
#include <QByteArray>
#include <QString>
#include <QDebug>

AIClient::AIClient(QObject *parent) : QObject(parent)
{
    m_networkManager = new QNetworkAccessManager(this);
    m_settings = new QSettings("AIConfig.ini", QSettings::IniFormat, this);

    connect(m_networkManager, &QNetworkAccessManager::finished,
            this, &AIClient::onReplyFinished);
}

void AIClient::sendQuestion(const QString &question, const QString &conversationId)
{
    QString apiKey = getApiKey();
    if (apiKey.isEmpty()) {
        emit errorOccurred("请先在设置中配置API密钥");
        return;
    }

    QUrl url(getApiUrl());
    QNetworkRequest request(url);

    // 设置请求头
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    request.setRawHeader("Authorization", QString("Bearer %1").arg(apiKey).toUtf8());

    // 构建请求数据
    QByteArray data = buildRequestData(question, conversationId);

    // 发送POST请求
    m_networkManager->post(request, data);
}

void AIClient::setApiKey(const QString &apiKey)
{
    m_settings->setValue("API/api_key", apiKey);
}

QString AIClient::getApiKey() const
{
    return m_settings->value("API/api_key", "").toString();
}

QString AIClient::getApiUrl() const
{
    // DeepSeek API地址
    return "https://api.deepseek.com/chat/completions";
}

QByteArray AIClient::buildRequestData(const QString &question, const QString &conversationId)
{
    QJsonObject rootObj;
    QJsonArray messagesArray;

    // 添加系统角色消息（可选）
    QJsonObject systemMsg;
    systemMsg["role"] = "system";
    systemMsg["content"] = "You are a helpful assistant";
    messagesArray.append(systemMsg);

    // 添加历史对话（保持上下文）
    if (m_conversationContexts.contains(conversationId)) {
        QStringList context = m_conversationContexts[conversationId];
        for (int i = 0; i < context.size(); i += 2) {
            QJsonObject userMsg;
            userMsg["role"] = "user";
            userMsg["content"] = context[i];
            messagesArray.append(userMsg);

            if (i + 1 < context.size()) {
                QJsonObject aiMsg;
                aiMsg["role"] = "assistant";
                aiMsg["content"] = context[i + 1];
                messagesArray.append(aiMsg);
            }
        }
    }

    // 添加当前问题
    QJsonObject currentMsg;
    currentMsg["role"] = "user";
    currentMsg["content"] = question;
    messagesArray.append(currentMsg);

    rootObj["model"] = "deepseek-chat";  // 添加模型参数
    rootObj["messages"] = messagesArray;
    rootObj["temperature"] = 0.7; // 温度参数，控制回答的随机性
    rootObj["stream"] = false;    // 是否流式输出

    QJsonDocument doc(rootObj);
    return doc.toJson();
}

void AIClient::onReplyFinished(QNetworkReply *reply)
{
    if (reply->error() != QNetworkReply::NoError) {
        emit errorOccurred("网络错误: " + reply->errorString());
        reply->deleteLater();
        return;
    }

    QByteArray data = reply->readAll();
    reply->deleteLater();

    // 解析JSON响应
    QJsonDocument doc = QJsonDocument::fromJson(data);
    if (doc.isNull()) {
        emit errorOccurred("解析响应失败");
        return;
    }

    QJsonObject rootObj = doc.object();
    if (rootObj.contains("error")) {
        QJsonObject errorObj = rootObj["error"].toObject();
        QString errorMsg = errorObj["message"].toString();
        emit errorOccurred("API错误: " + errorMsg);
        return;
    }

    if (rootObj.contains("choices")) {
        QJsonArray choices = rootObj["choices"].toArray();
        if (!choices.isEmpty()) {
            QJsonObject choice = choices.first().toObject();
            if (choice.contains("message")) {
                QJsonObject message = choice["message"].toObject();
                QString answer = message["content"].toString();
                emit answerReady(answer);
            } else {
                emit errorOccurred("未找到回答内容");
            }
        } else {
            emit errorOccurred("未找到回答内容");
        }
    } else {
        emit errorOccurred("响应格式错误");
    }
}

void AIClient::updateConversationContext(const QString &conversationId,
                                        const QString &question, const QString &answer)
{
    if (!m_conversationContexts.contains(conversationId)) {
        m_conversationContexts[conversationId] = QStringList();
    }

    // 限制上下文长度，避免请求过大
    QStringList &context = m_conversationContexts[conversationId];
    context.append(question);
    context.append(answer);

    // 只保留最近10轮对话（20条消息）
    while (context.size() > 20) {
        context.removeFirst();
        context.removeFirst();
    }
}